package com.example.demo.controller;

import com.example.demo.service.ProductOrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("api/v1/order")
public class OrderController {


    @Autowired
    private ProductOrderService productOrderService;
    @Autowired
    private StringRedisTemplate redisTemplate;


    @RequestMapping("save")
    @HystrixCommand(fallbackMethod = "saveOrderFail")
    public Object save(@RequestParam("user_id")int userId, @RequestParam("product_id") int productId){
        Map map=new HashMap<String,Objects>();
        map.put("state",0);
        map.put("value",productOrderService.save(userId, productId));
        return map;
    }

    @RequestMapping("save2")
    @HystrixCommand(fallbackMethod = "saveOrderFail2")
    public Object save2(@RequestParam("user_id")int userId, @RequestParam("product_id") int productId, HttpServletRequest request){
        Map map=new HashMap<String,Objects>();
        map.put("state",0);
        map.put("value",productOrderService.save2(userId, productId));
        return map;
    }

    public Map saveOrderFail(int userId, int productId) {
        Map map=new HashMap<String,Objects>();
        map.put("state",0);
        map.put("value","saveOrderFail当前系统拥挤，您被挤出来了");
        return map;

    }

    public Map saveOrderFail2(int userId, int productId, HttpServletRequest request) {
        //监控报警
        String saveOrderKye = "save-order";
        String sendValue = redisTemplate.opsForValue().get(saveOrderKye);
        final String ip = request.getRemoteAddr()+":"+ request.getLocalPort();
       // System.out.println("getLocalAddr:"+request.getLocalAddr()+":"+request.getLocalPort());

        new Thread( ()->{
            if (StringUtils.isBlank(sendValue)) {
                System.out.println("紧急短信，用户下单失败，请离开查找原因,ip地址是="+ip);
                //发送一个http请求，调用短信服务 TODO
                redisTemplate.opsForValue().set(saveOrderKye, "save-order-fail", 20, TimeUnit.SECONDS);
            }else{
                System.out.println("已经发送过短信，20秒内不重复发送");
            }
        }).start();
        Map map=new HashMap<String,Objects>();
        map.put("state",0);
        map.put("value","saveOrderFail2当前系统拥挤，您被挤出来了");

        return map;

    }

}
